<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Dapp</title>
  </head>
  <body>
    <script type="text/javascript">

      window.onload = function() {
        window.web3 = window.parent.web32;
        window.dispatchEvent(new Event("web3Ready"));
        window.esss = window.parent.esss;

        const originalError = console.error;
        const originalLog = console.log;
        const originalWarning = console.warn;
        const originalInfo = console.info;

        const cnsl = window.parent.cnsl;

        console.error = function (error) {
          cnsl(error.toString(), "error");
          originalError.apply(console, arguments);
        };
        console.log = function (...args) {
          args.forEach(cnsl);
          originalLog.apply(console, args);
        };
        console.warn = function (...args) {
          args.forEach(cnsl);
          originalWarning.apply(console, args);
        };
        console.info = function (...args) {
          args.forEach(cnsl);
          originalInfo.apply(console, args);
        };

        var head  = document.getElementsByTagName("head")[0];
        for (let i = 0; i < window.parent.cssLibs.length; i++) {
          var link  = document.createElement("link");
          link.rel  = "stylesheet";
          link.type = "text/css";
          link.href = window.parent.cssLibs[i];
          link.media = "all";
          head.appendChild(link);
        }

        document.body.innerHTML = window.parent.htmlSrc;

        var style = document.createElement("style");
        style.innerHTML = window.parent.cssSrc;
        document.body.appendChild(style);

        let jsReadyCount = 0;
        for (let i = 0; i < window.parent.jsLibs.length; i++) {
          var script = document.createElement("script");
          script.type = "text/javascript";
          script.src = window.parent.jsLibs[i];
          script.addEventListener("load", () => {
            jsReadyCount++;
          });
          script.addEventListener("error", () => {
            jsReadyCount++;
          });
          document.body.appendChild(script);
        }

        function launchJs() {
          setTimeout(() => {
            if (jsReadyCount === window.parent.jsLibs.length) {
              var script = document.createElement("script");
              script.type = "text/javascript";
              script.innerHTML = window.parent.jsSrc;
              document.body.appendChild(script);
              window.dispatchEvent(new Event("web3Ready"));
            } else {
              launchJs();
            }
          }, 100);
        }
        launchJs();
      };
    </script>
  </body>
</html>
